<template>
  <div class="document-upload">
    <!-- 文件上传区域 -->
    <el-upload
      ref="uploadRef"
      class="upload-area"
      :class="{ 'is-dragover': isDragover }"
      drag
      multiple
      :auto-upload="false"
      :file-list="fileList"
      :on-change="handleFileChange"
      :on-remove="handleFileRemove"
      :before-upload="beforeUpload"
      accept=".pdf,.doc,.docx,.ppt,.pptx,.jpg,.jpeg,.png"
    >
      <div class="upload-content">
        <el-icon class="upload-icon"><UploadFilled /></el-icon>
        <div class="upload-text">
          <p class="upload-primary">拖拽文件到此处，或<span class="upload-link">点击选择文件</span></p>
          <p class="upload-hint">支持 PDF、Word、PPT、图片等格式，单文件最大 50MB</p>
        </div>
      </div>
    </el-upload>

    <!-- 文件列表 -->
    <div v-if="fileList.length" class="file-list">
      <div class="list-header">
        <span>已选择文件 ({{ fileList.length }})</span>
        <el-button text type="danger" @click="clearFiles">
          <el-icon><Delete /></el-icon>
          清空
        </el-button>
      </div>
      
      <div class="file-items">
        <div
          v-for="(file, index) in fileList"
          :key="index"
          class="file-item"
        >
          <div class="file-info">
            <div class="file-icon" :class="getFileType(file.name)">
              <el-icon>
                <Document v-if="getFileType(file.name) === 'pdf'" />
                <Reading v-else-if="getFileType(file.name) === 'doc'" />
                <Present v-else-if="getFileType(file.name) === 'ppt'" />
                <Picture v-else />
              </el-icon>
            </div>
            <div class="file-details">
              <div class="file-name">{{ file.name }}</div>
              <div class="file-size">{{ formatFileSize(file.size) }}</div>
            </div>
          </div>
          
          <div class="file-progress" v-if="file.status === 'uploading'">
            <el-progress :percentage="file.percentage" :stroke-width="4" />
          </div>
          
          <div class="file-actions">
            <el-button
              circle
              size="small"
              type="danger"
              @click="removeFile(index)"
            >
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 文档属性设置 -->
    <div v-if="fileList.length" class="document-settings">
      <el-form :model="uploadForm" label-width="80px" label-position="left">
        <el-form-item label="关联项目">
          <el-select
            v-model="uploadForm.projectId"
            placeholder="选择项目（可选）"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="project in projectStore.projects"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="文档标签">
          <el-select
            v-model="uploadForm.tags"
            multiple
            filterable
            allow-create
            placeholder="添加标签"
            style="width: 100%"
          >
            <el-option
              v-for="tag in suggestedTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="文档描述">
          <el-input
            v-model="uploadForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入文档描述（可选）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="upload-actions">
      <el-button @click="$emit('cancel')">取消</el-button>
      <el-button
        type="primary"
        :loading="uploading"
        :disabled="!fileList.length"
        @click="startUpload"
      >
        <el-icon v-if="!uploading"><Upload /></el-icon>
        {{ uploading ? '上传中...' : `开始上传 (${fileList.length})` }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useDocumentStore } from '@/store/document'
import { useProjectStore } from '@/store/project'
import { ElMessage } from 'element-plus'
import {
  UploadFilled, Document, Reading, Present, Picture,
  Delete, Close, Upload
} from '@element-plus/icons-vue'

// 定义 emits
const emit = defineEmits(['success', 'cancel'])

// 使用 stores
const documentStore = useDocumentStore()
const projectStore = useProjectStore()

// 响应式数据
const uploadRef = ref()
const fileList = ref([])
const isDragover = ref(false)
const uploading = ref(false)

const uploadForm = reactive({
  projectId: null,
  tags: [],
  description: ''
})

// 建议的标签
const suggestedTags = ref([
  '技术方案', '投标', '医疗设备', '产品介绍', '说明书',
  '培训', '考试', '评分标准', 'SaaS平台', '采购清单',
  '现场照片', '实施', '记录'
])

// 计算属性
const totalSize = computed(() => {
  return fileList.value.reduce((total, file) => total + file.size, 0)
})

// 方法
const getFileType = (fileName) => {
  const ext = fileName.split('.').pop().toLowerCase()
  if (['pdf'].includes(ext)) return 'pdf'
  if (['doc', 'docx'].includes(ext)) return 'doc'
  if (['ppt', 'pptx'].includes(ext)) return 'ppt'
  if (['jpg', 'jpeg', 'png', 'gif'].includes(ext)) return 'img'
  return 'unknown'
}

const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const handleFileChange = (file, files) => {
  fileList.value = files
}

const handleFileRemove = (file, files) => {
  fileList.value = files
}

const removeFile = (index) => {
  fileList.value.splice(index, 1)
}

const clearFiles = () => {
  fileList.value = []
  uploadRef.value.clearFiles()
}

const beforeUpload = (file) => {
  // 检查文件大小
  const maxSize = 50 * 1024 * 1024 // 50MB
  if (file.size > maxSize) {
    ElMessage.error(`文件 ${file.name} 大小超过 50MB 限制`)
    return false
  }
  
  // 检查文件类型
  const allowedTypes = ['.pdf', '.doc', '.docx', '.ppt', '.pptx', '.jpg', '.jpeg', '.png']
  const fileExt = '.' + file.name.split('.').pop().toLowerCase()
  if (!allowedTypes.includes(fileExt)) {
    ElMessage.error(`不支持的文件类型: ${fileExt}`)
    return false
  }
  
  return true
}

const startUpload = async () => {
  if (!fileList.value.length) {
    ElMessage.warning('请选择要上传的文件')
    return
  }
  
  uploading.value = true
  
  try {
    // 模拟上传过程
    for (let i = 0; i < fileList.value.length; i++) {
      const file = fileList.value[i]
      
      // 设置上传状态
      file.status = 'uploading'
      file.percentage = 0
      
      // 模拟上传进度
      const uploadProgress = setInterval(() => {
        if (file.percentage < 100) {
          file.percentage += Math.random() * 20
          if (file.percentage >= 100) {
            file.percentage = 100
            file.status = 'success'
            clearInterval(uploadProgress)
          }
        }
      }, 100)
      
      // 等待上传完成
      await new Promise(resolve => {
        const checkComplete = setInterval(() => {
          if (file.status === 'success') {
            clearInterval(checkComplete)
            resolve()
          }
        }, 50)
      })
      
      // 添加到文档库
      const newDocument = {
        title: file.name,
        type: getFileType(file.name),
        size: formatFileSize(file.size),
        sizeBytes: file.size,
        project: uploadForm.projectId ? 
          projectStore.getProjectById(uploadForm.projectId)?.name : '未分类',
        projectId: uploadForm.projectId,
        tags: uploadForm.tags,
        description: uploadForm.description || '通过系统上传的文档',
        author: '当前用户',
        filePath: `/uploads/${file.name}`
      }
      
      documentStore.addDocument(newDocument)
      
      // 如果选择了项目，关联到项目
      if (uploadForm.projectId) {
        projectStore.addDocumentToProject(uploadForm.projectId, newDocument.id)
      }
    }
    
    ElMessage.success(`成功上传 ${fileList.value.length} 个文件`)
    emit('success')
    
  } catch (error) {
    ElMessage.error('上传失败: ' + error.message)
  } finally {
    uploading.value = false
  }
}

// 自动建议标签
const autoSuggestTags = (fileName) => {
  const name = fileName.toLowerCase()
  const suggestions = []
  
  if (name.includes('技术') || name.includes('方案')) suggestions.push('技术方案')
  if (name.includes('投标') || name.includes('招标')) suggestions.push('投标')
  if (name.includes('培训')) suggestions.push('培训')
  if (name.includes('考试') || name.includes('测试')) suggestions.push('考试')
  if (name.includes('说明') || name.includes('手册')) suggestions.push('说明书')
  if (name.includes('介绍') || name.includes('产品')) suggestions.push('产品介绍')
  
  return suggestions
}

// 监听文件变化，自动建议标签
const updateSuggestedTags = () => {
  const allSuggestions = new Set(suggestedTags.value)
  
  fileList.value.forEach(file => {
    const suggestions = autoSuggestTags(file.name)
    suggestions.forEach(tag => allSuggestions.add(tag))
  })
  
  suggestedTags.value = Array.from(allSuggestions)
}
</script>

<style lang="scss" scoped>
.document-upload {
  .upload-area {
    margin-bottom: 20px;
    
    :deep(.el-upload-dragger) {
      border-radius: 8px;
      border: 2px dashed var(--el-border-color);
      background: var(--el-fill-color-lighter);
      transition: all 0.3s;
      
      &:hover, &.is-dragover {
        border-color: var(--el-color-primary);
        background: var(--el-color-primary-light-9);
      }
    }
  }
  
  .upload-content {
    padding: 40px 20px;
    text-align: center;
    
    .upload-icon {
      font-size: 48px;
      color: var(--el-color-primary);
      margin-bottom: 16px;
    }
    
    .upload-text {
      .upload-primary {
        font-size: 16px;
        color: var(--el-text-color-primary);
        margin-bottom: 8px;
        
        .upload-link {
          color: var(--el-color-primary);
          cursor: pointer;
          
          &:hover {
            text-decoration: underline;
          }
        }
      }
      
      .upload-hint {
        font-size: 14px;
        color: var(--el-text-color-secondary);
        margin: 0;
      }
    }
  }
  
  .file-list {
    margin-bottom: 20px;
    
    .list-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      padding-bottom: 8px;
      border-bottom: 1px solid var(--el-border-color-lighter);
      
      span {
        font-weight: 500;
        color: var(--el-text-color-primary);
      }
    }
    
    .file-items {
      max-height: 200px;
      overflow-y: auto;
    }
  }
  
  .file-item {
    display: flex;
    align-items: center;
    padding: 12px;
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 6px;
    margin-bottom: 8px;
    background: var(--el-bg-color);
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .file-info {
      display: flex;
      align-items: center;
      flex: 1;
      
      .file-icon {
        width: 32px;
        height: 32px;
        border-radius: 6px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 12px;
        font-size: 16px;
        color: white;
        
        &.pdf {
          background: var(--el-color-danger);
        }
        
        &.doc {
          background: var(--el-color-primary);
        }
        
        &.ppt {
          background: var(--el-color-warning);
        }
        
        &.img {
          background: var(--el-color-success);
        }
        
        &.unknown {
          background: var(--el-color-info);
        }
      }
      
      .file-details {
        flex: 1;
        
        .file-name {
          font-size: 14px;
          color: var(--el-text-color-primary);
          margin-bottom: 4px;
          word-break: break-all;
        }
        
        .file-size {
          font-size: 12px;
          color: var(--el-text-color-secondary);
        }
      }
    }
    
    .file-progress {
      flex: 1;
      margin: 0 12px;
    }
    
    .file-actions {
      margin-left: 8px;
    }
  }
  
  .document-settings {
    margin-bottom: 20px;
    padding: 16px;
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 6px;
    background: var(--el-fill-color-lighter);
  }
  
  .upload-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding-top: 16px;
    border-top: 1px solid var(--el-border-color-lighter);
  }
}
</style>